#!/usr/bin/env python
# encoding: utf-8

"""
@author: Cao
@contact: caoqiang0012@163.com
@file: RobotStateChecking.py
@time: 28/05/2018 3:19 PM
"""
# !/usr/bin/env python
# encoding: utf-8


import paramiko
from Public import SimpleSSH
import time
import sys
from prettytable import PrettyTable


simplessh = SimpleSSH.SimpleSSH()

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())


#simplessh = SimpleSSH.SimpleSSH()
num = input("Please select your action when Robot is stopped:\n 1: Restart\n 2: Keep as it is\n:")

if num == '1':
    print('\nYour Choice is "Restart"')
else:
    print('\nYour Choice is "Keep As It Is"')

table = PrettyTable(["ID", "Robots", "Old_State", "New_State", "Disk_Usage"])
table.align["ID"] = 'r'
table.align["Disk_Usage"] = 'r'

print('\nChecking in progress ', end='')

id = 1

try:

    for robot in simplessh.getRobotInfo()['robots']:
        #print('\n' + 'Connecting to ' + robot['username'])

        ssh.connect(robot['url'], 22, robot['username'], robot['password'])

        print('>>' + str(id) + '>> ', end='')
        sys.stdout.flush()

        stdin, stdout, stderr = ssh.exec_command("source /robots/machine-global-cache-for-personal-service/bashrc\n/robots/machine-global-cache-for-personal-service/usr/local/services/tools/bin/robot-control status")

        lines = stdout.readlines()
        # print(lines)
        if '====' in lines[7]:
            x = 7
        else:
            x = 8

        # print('x = ' + str(x))
        time.sleep(2)

        stdin, stdout, stderr = ssh.exec_command("df -h")

        df = stdout.readlines()

        # print(df)
        # print(df.index(robot['username']))
        username = robot['username']

        for i in range(len(df)):
            if '/home/' + username in df[i]:
                indexnum = df[i].find('%')
                usage = df[i][indexnum - 2:indexnum + 1]
                if usage > '80%':
                    usage = '* ' + str(usage)
                # print(usage)
                # print(df[40:43])
            else:
                # comments = 'NA'
                pass


        dict = {}

        for i in range(1, x):

            line = lines[i].strip('\n').split(": ")
            # print(line)

            dict[line[0]] = line[1]

        # print('*' * 30)
        # print('The ' + robot['username'] + ' current state is: ' + dict['State'])
        # print('*' * 30 + '\n')

        state = dict['State']


        if state == 'stopped':

            id = '* ' + str(id)

            if num == '1':

                ssh.exec_command("source /robots/machine-global-cache-for-personal-service/bashrc\n/robots/machine-global-cache-for-personal-service/usr/local/services/tools/bin/robot-control start")

                time.sleep(3)

                stdin, stdout, stderr = ssh.exec_command("source /robots/machine-global-cache-for-personal-service/bashrc\n/robots/machine-global-cache-for-personal-service/usr/local/services/tools/bin/robot-control status")

                lines2 = stdout.readlines()

                dict2 = {}

                for i in range(2, 8):

                    line2 = lines2[i].strip('\n').split(": ")

                    dict2[line2[0]] = line2[1]

                # print('\n')
                # print('*' * 30)
                # print('The ' + robot['username'] + ' new state is: ' + dict2['State'])
                table.add_row([id, robot['username'], dict['State'], dict2['State'], usage])
            else:
                table.add_row([id, robot['username'], dict['State'], dict['State'], usage])

            id = int(id[2])

        else:
            table.add_row([id, robot['username'], dict['State'], dict['State'], usage])

        id += 1

    ssh.close()
    print('\n')
    print(table)

except:

    print('\n')
    print(table)